package com.novel.framework.aspectj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.novel.common.exception.DemoModeException;
import com.novel.framework.config.ProjectConfig;
import com.novel.framework.utils.servlet.ServletUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 演示模式切面
 *
 * @author novel
 * @date 2019/12/5
 */
@Aspect
@Component
public class DemoModeAspect {
    private static final Logger log = LoggerFactory.getLogger(DemoModeAspect.class);

    // 配置织入点
    @Pointcut("execution(public * com.novel..controller.*.*(..))" +
            "&&!execution(public * com.novel.system..controller.LoginController.*(..))")
    public void pointCut() {
    }

    /**
     * 前置通知 用于拦截操作
     *
     * @param joinPoint 切点
     */
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        if (ProjectConfig.getDemoEnabled()) {
            String method = ServletUtils.getRequest().getMethod();
            if ("delete".equalsIgnoreCase(method) || "put".equalsIgnoreCase(method)) {
                throw new DemoModeException();
            }
            String uri = ServletUtils.getRequest().getRequestURI();
            if (uri.contains("menu/add")) {
                throw new DemoModeException();
            }

            if (uri.contains("monitor/job/add") || uri.contains("monitor/job/edit")) {
                Object[] args = joinPoint.getArgs();
                if (args.length>0 ){
                    JSONObject json = (JSONObject) JSON.toJSON(args[0]);
                    String invokeTarget = json.getString("invokeTarget");
                    if (!invokeTarget.contains("novelTask.novelParams")&&!invokeTarget.contains("novelTask.novelMultipleParams")&&!invokeTarget.contains("novelTask.novelNoParams")){
                        throw new DemoModeException("演示模式下只能添加默认的任务字符串");
                    }
                }
            }
        }
    }
}
